<template>
  <el-dialog
    :model-value="showAddVisible"
    :roomName="props.editInfo.id ? '编辑直播间' : '新增直播间'"
    width="700"
    :close-on-click-modal="false"
    @close="resetForm"
  >
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="排序" prop="sortOrder">
        <el-input v-model="ruleForm.sortOrder" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="流名称" prop="streamName">
        <el-input v-model="ruleForm.streamName" placeholder="仅支持英文字母、数字和符号" />
      </el-form-item>
      <el-form-item label="发布人" prop="creatorId">
        <el-select v-model="ruleForm.creatorId" clearable>
          <el-option
            v-for="item in creatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="直播标题" prop="roomName">
        <el-input v-model="ruleForm.roomName" type="textarea" :rows="6" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="标签">
        <el-input
          v-model="ruleForm.tags"
          type="textarea"
          :rows="6"
          placeholder="多个标签请用英文逗号分割"
        />
      </el-form-item>
      <el-form-item label="直播简介">
        <el-input v-model="ruleForm.roomIntro" type="textarea" :rows="6" placeholder="" />
      </el-form-item>
      <el-form-item label="直播封面" prop="coverImage">
        <el-input v-model="ruleForm.coverImage" style="display: none"></el-input>
        <div class="avatar-uploader" @click="showImageChooseDialog = true">
          <el-image
            v-if="ruleForm.coverImage"
            :src="ruleForm.coverImage"
            class="avatar"
            fit="contain"
          ></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"
            ><el-icon> <Plus /> </el-icon
          ></i>
          <div v-if="ruleForm.coverImage" class="mask">替换</div>
          <el-icon
            v-if="ruleForm.coverImage"
            class="del-image"
            :size="20"
            @click.stop="handleDelImg"
          >
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item>

      <el-form-item label="车型" prop="carModelId">
        <el-select v-model="ruleForm.carIds" clearable>
          <el-option
            v-for="item in carList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科目类型" prop="categoryIds">
        <el-select v-model="ruleForm.categoryIds" clearable>
          <el-option value="1" label="科目一" />
          <el-option value="2" label="科目二" />
          <el-option value="3" label="科目三" />
          <el-option value="4" label="科目四" />
          <el-option value="5" label="注销恢复" />
          <el-option value="6" label="满分学习" />
          <el-option value="7" label="三力测试" />
        </el-select>
      </el-form-item>

      <el-form-item label="计划开播时间">
        <el-date-picker
          style="width: 100%"
          v-model="ruleForm.scheduledTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder=""
        />
      </el-form-item>

      <el-form-item label="推流地址" prop="pushUrl">
        <el-input v-model="ruleForm.pushUrl">
          <template #append>
            <div class="video-uploader" @click="getPullOrPushUrl('01')">
              <el-button style="color: #2b8dfa" type="primary">获取推流地址</el-button>
            </div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="拉流地址" prop="pullUrl">
        <el-input v-model="ruleForm.pullUrl">
          <template #append>
            <div class="video-uploader" @click="getPullOrPushUrl('0203')">
              <el-button style="color: #2b8dfa" type="primary">获取拉流地址</el-button>
            </div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="状态" prop="roomStatus">
        <el-switch v-model="ruleForm.roomStatus" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)"
          >确认</el-button
        >
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <image-selected-dialog
    v-if="showImageChooseDialog"
    :single-type="selectImageSingle"
    :show-image-choose-dialog="showImageChooseDialog"
    @close-dialog="handleCloseImageDialog"
    :operationType="false"
  ></image-selected-dialog>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
  import { addLiveRoom, putLiveRoom, getLiveRoomUrl, getCreatorOptions } from '@/api/marketing'
  import { cardsType } from '@/api/userStudentsApi'

  const props = defineProps({
    showAddVisible: {
      type: Boolean
    },
    editInfo: {
      type: Object,
      default: () => {
        return {
          id: ''
        }
      }
    }
  })

  const emit = defineEmits(['closeDialog'])
  const editLoading = ref(false)

  interface RuleForm {
    sortOrder: string
    roomName: string
    tags: string
    roomStatus: number
    coverImage: string
    pushUrl: string
    pullUrl: string
    carIds: string
    categoryIds: string
    scheduledTime: string
    roomIntro: string
    streamName: string
    creatorId: string
  }

  const ruleFormRef = ref<FormInstance>()

  const ruleForm = reactive<RuleForm>({
    sortOrder: '1',
    roomName: '',
    tags: '',
    roomStatus: 1,
    coverImage: '',
    pushUrl: '',
    pullUrl: '',
    carIds: '',
    categoryIds: '',
    scheduledTime: '',
    roomIntro: '',
    streamName: '',
    creatorId: ''
  })

  interface CarItem {
    value: string | number
    label: string
    tag: string
  }
  const carList = ref<CarItem[]>([])
  const creatorList = ref<any[]>([])
  const showImageChooseDialog = ref(false)
  const selectImageSingle = ref(true)
  const handleCloseImageDialog = (value: any) => {
    if (value && value.fileUrl) {
      ruleForm.coverImage = value.fileUrl
    }
    showImageChooseDialog.value = false
  }

  const handleDelImg = () => {
    ruleForm.coverImage = ''
  }

  const rules = reactive<FormRules<RuleForm>>({
    sortOrder: [{ required: true, message: '不能为空', trigger: 'blur' }],
    roomName: [{ required: true, message: '不能为空', trigger: 'blur' }],
    streamName: [
      { required: true, message: '请输入内容', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9\W]+$/,
        message: '仅支持英文字母、数字和符号',
        trigger: 'blur'
      }
    ],
    coverImage: [{ required: true, message: '不能为空', trigger: 'blur' }],
    pushUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
    pullUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
    roomStatus: [{ required: true, message: '不能为空', trigger: 'blur' }],
    creatorId: [{ required: true, message: '不能为空', trigger: 'change' }]
  })

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        if (props.editInfo.id) {
          handleEdit()
        } else {
          handleAdd()
        }
      } else {
      }
    })
  }

  async function handleAdd() {
    try {
      editLoading.value = true
      const res = await addLiveRoom(ruleForm)
      if (res.code === '00000') {
        emit('closeDialog', true)
        ElMessage.success('新增成功')
      }
    } catch (e) {
    } finally {
      editLoading.value = false
    }
  }

  async function handleEdit() {
    try {
      editLoading.value = true
      const res = await putLiveRoom(ruleForm, props.editInfo.id)
      if (res.code === '00000') {
        emit('closeDialog', true)
        ElMessage.success('编辑成功')
      }
    } catch (e) {
    } finally {
      editLoading.value = false
    }
  }

  const resetForm = () => {
    emit('closeDialog')
  }

  const getCardType = async () => {
    const res = await cardsType()
    carList.value = res.data
  }

  async function getCreatorList() {
    const res = await getCreatorOptions({})
    if (res.code === '00000') {
      creatorList.value = res.data
    }
  }

  async function getPullOrPushUrl(type: string) {
    if (!ruleForm.streamName) {
      ElMessage.warning('请输入流名称')
      return
    }

    const res = await getLiveRoomUrl({
      type,
      streamName: ruleForm.streamName,
      validDays: 1
    })
    if (res.code === '00000') {
      if (type === '01') {
        ruleForm.pushUrl = res.data
      } else if (type === '0203') {
        ruleForm.pullUrl = res.data
      }
    }
  }

  onMounted(() => {
    if (props.editInfo.id) {
      ruleForm.sortOrder = props.editInfo.sortOrder
      ruleForm.roomName = props.editInfo.roomName
      ruleForm.tags = props.editInfo.tags
      ruleForm.roomStatus = props.editInfo.roomStatus
      ruleForm.coverImage = props.editInfo.coverImage
      ruleForm.pushUrl = props.editInfo.pushUrl
      ruleForm.pullUrl = props.editInfo.pullUrl
      ruleForm.carIds = props.editInfo.carIds
      ruleForm.categoryIds = props.editInfo.categoryIds
      ruleForm.scheduledTime = props.editInfo.scheduledTime
      ruleForm.roomIntro = props.editInfo.roomIntro
      ruleForm.streamName = props.editInfo.streamName
      ruleForm.creatorId = props.editInfo.creatorId
    }

    getCardType()
    getCreatorList()
  })
</script>

<style scoped lang="scss">
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;

    .mask {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 24px;
      background-color: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s ease;
      color: #fff;
      font-size: 12px;
    }

    .del-image {
      display: none;
      position: absolute;
      top: 0;
      right: 0;
      cursor: pointer;
      color: #8c939d;
    }

    &:hover .mask {
      opacity: 1;
    }

    &:hover .del-image {
      display: block;
    }
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
